﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace Eventless.WinForms
{
    public class CheckedListBoxItem
    {
        public readonly IWriteable<string> Text = new Writeable<string>();
        public readonly IWriteable<CheckState> State = new Writeable<CheckState>();
        public readonly IWriteable<bool> IsChecked;

        private readonly List<CheckedListBox> _boundTo = new List<CheckedListBox>();

        public CheckedListBoxItem()
        {
            IsChecked = Computed.From(
                () => State.Value == CheckState.Checked,
                v => State.Value = v ? CheckState.Checked : CheckState.Unchecked);

            State.Changed += () =>
                {
                    foreach (var list in _boundTo)
                        list.SetItemCheckState(list.Items.IndexOf(this), State.Value);
                };

            Text.Changed += () =>
                {
                    foreach (var list in _boundTo)
                        list.Invalidate();
                };
        }

        public override string ToString()
        {
            return Text.Value ?? string.Empty;
        }

        public CheckedListBoxItem Bind(CheckedListBox checkedListBox)
        {
            if (_boundTo.Contains(checkedListBox))
                throw new InvalidOperationException("CheckedListBoxItem cannot appear twice on same list: " + this);

            _boundTo.Add(checkedListBox);
            return this;
        }

        public void Unbind(CheckedListBox checkedListBox)
        {
            _boundTo.Remove(checkedListBox);
        }
    }
}